const chalk = require('chalk');
const path = require('path');
const util = require('util');
const { rimraf } = require('rimraf');
const prompts = require('prompts');
const child_process = require('child_process');

const fs = require('fs-extra');

chalk.level = 1;

module.exports = async function (option) {
  const projectName = await getProjectName()
  // 获取当前执行目录
  const cwd = process.cwd();
  const targetDir = path.join(cwd, projectName);
  if (fs.existsSync(targetDir)) {
    if (option.force) {
      await fs.remove(targetDir);
    } else {
      let { action } = await prompts([
        {
          name: 'action',
          type: 'select',
          message: '当前文件名重复是否覆盖？',
          choices: [
            { title: '覆盖', value: 'overwrite' },
            { title: '取消', value: 'cancel' }
          ]
        }
      ]);

      if (!action || action === 'cancel') {
        console.log(`\r\n 取消构建`);
        return;
      } else if (action === 'overwrite') {
        console.log(`\r\n 正在移除...`);
        await rimraf(targetDir);
      }
    }
  }

  let temp = await fetchRepo();
  let tag = await fetchVersion(temp);
  

  // 在这里写入你的git仓库地址
  // 注意：需要使用github,或者是gitlab的地址
  const gitbaseurl = 'https://gitee.com/wstee';
  async function downloadtemp(temp, tag){
    const exec = util.promisify(child_process.exec);
    await exec(`git clone ${tag?'-b '+tag:''} ${gitbaseurl}/${temp}.git ${projectName}`);
  }
  await downloadtemp(temp, tag);
  
  const gitDir = path.join(targetDir, '.git');
  await rimraf(gitDir);
  console.log(`\r\n ${chalk.green(`cd ${projectName} & pnpm install`)}`);
  process.exit(0)
}

const tempTag = {
  'vue-template': [{ title: '基础版', value: 'main' },{ title: '大屏项目echarts', value: 'big-screen'}]
}
async function getProjectName(){ 
  let { projectName } = await prompts({
       name:'projectName',
       type:'text',
       message:'请输入项目名',
       default: 'wst'
   })
   return projectName
}

async function fetchVersion(temp){ 
  let { tag } = await prompts({
       name:'tag',
       type:'select',
       choices: tempTag[temp],
       message:'请选择版本'
   })
   return tag
}

async function fetchRepo(){  
  let {temp} = await prompts({
       name:'temp',
       type:'select',
       choices:[{ title: 'vue-template', value: 'vue-template' }],
       message:'请选择模板!'
   })
   return temp;
}

